import numpy as np
import matplotlib.pyplot as plt
from pyswarm import pso
import os
import random


plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题
plt.rc('font', size=10)
plt.rc('font', family='SimHei')

# 通用常数
interval = 1  # 投弹时间间隔
v_down = 3  # 云团下降速度
r_effective = 10  # 有效遮蔽半径
t_effective = 20  # 有效遮蔽时间
v_missile = 300  # 导弹速度
r_target = 7  # 目标半径
H_target = 10  # 目标高度
target = np.array([0, 200, 0])  # 目标底部圆心坐标
M1 = np.array([20000, 0, 2000])
M2 = np.array([19000, 600, 2100])
M3 = np.array([18000, -600, 1900])
FY1 = np.array([17800, 0, 1800])
FY2 = np.array([12000, 1400, 1400])
FY3 = np.array([6000, -3000, 700])
FY4 = np.array([11000, 2000, 1800])
FY5 = np.array([13000, -2000, 1300])
v_range = np.array([70, 140])  # 无人机速度范围
g = 9.8  # 重力加速度
# target_point = np.array([
#     [(1 / 2) ** 0.5 * r_target, (1 / 2) ** 0.5 * r_target + 200, 0],
#     [-(1 / 2) ** 0.5 * r_target, (1 / 2) ** 0.5 * r_target + 200, 0],
#     [(1 / 2) ** 0.5 * r_target, -(1 / 2) ** 0.5 * r_target + 200, 0],
#     [-(1 / 2) ** 0.5 * r_target, -(1 / 2) ** 0.5 * r_target + 200, 0],
#     [(1 / 2) ** 0.5 * r_target, (1 / 2) ** 0.5 * r_target + 200, H_target],
#     [-(1 / 2) ** 0.5 * r_target, (1 / 2) ** 0.5 * r_target + 200, H_target],
#     [(1 / 2) ** 0.5 * r_target, -(1 / 2) ** 0.5 * r_target + 200, H_target],
#     [-(1 / 2) ** 0.5 * r_target, -(1 / 2) ** 0.5 * r_target + 200, H_target],
#     [(1 / 2) ** 0.5 * r_target, (1 / 2) ** 0.5 * r_target + 200, H_target / 2],
#     [-(1 / 2) ** 0.5 * r_target, (1 / 2) ** 0.5 * r_target + 200, H_target / 2],
#     [(1 / 2) ** 0.5 * r_target, -(1 / 2) ** 0.5 * r_target + 200, H_target / 2],
#     [-(1 / 2) ** 0.5 * r_target, -(1 / 2) ** 0.5 * r_target + 200, H_target / 2],
# ])
t_total = np.linalg.norm(M1) / 300  # 从0开始到导弹击中目标的总用时
precision = 0.01  # 时间精度
target_point = np.array([
    [0, 200, 0]
])


# 传入M1的初始坐标（也即可确定其飞行方向）和经过的时间，返回其在给定时间下的坐标
def get_M1_coordinate(coordinate_0, t, v=None):
    if not v:
        v = -coordinate_0 / np.linalg.norm(coordinate_0) * v_missile
    else:
        v = v / np.linalg.norm(v) * v_missile
    return coordinate_0 + v * t


# 传入FY1的坐标和经过的时间，返回它投射的第i枚烟雾弹中心的坐标
def get_FY1_coordinate(coordinate_0, t, i, v_1, t_1, t_2, theta):
    t_drop = 0
    for j in range(i + 1):
        t_drop += t_1[j]
    t_explosion = t_2[i]
    if t < t_drop + t_explosion or t > t_drop + t_explosion + t_effective:
        return [None, None, None]
    else:
        v = np.array([np.cos(theta), np.sin(theta), 0]) * v_1
        delta_t = t - t_drop - t_explosion
        coordinate = coordinate_0 + v * (t_drop + t_explosion)
        coordinate[2] -= 1 / 2 * g * (t_explosion ** 2)
        coordinate[2] -= delta_t * v_down
        return coordinate


def collision_detection(coordinate_missile, coordinate_0, t, v_1, t_1, t_2, theta):
    global target_point, r_effective
    count_collision = 0
    for target in target_point:
        for i in range(3):
            coordinate_bomb = get_FY1_coordinate(coordinate_0, t, i, v_1, t_1, t_2, theta)
            if coordinate_bomb[0] == None:
                continue
            l_1 = coordinate_bomb - target
            l_2 = coordinate_missile - target
            molecule = np.cross(l_1, l_2)
            denominator = np.linalg.norm(l_2)
            d = np.linalg.norm(molecule) / denominator
            if d < r_effective:
                missile_to_target = -coordinate_missile  # 由导弹指向目标
                missile_to_bomb = coordinate_bomb - coordinate_missile  # 由导弹指向烟幕弹
                cos = np.dot(missile_to_target, missile_to_bomb)
                if cos > 0 or np.linalg.norm(missile_to_bomb) < r_effective:  # 余弦值大于0，是锐角，或者导弹和烟幕弹之间的距离小于有效半径
                    count_collision += 1
                    break
    return count_collision


# 飞行方向、飞行速度、烟幕干扰弹投放点、烟幕干扰弹起爆点
def fun(theta, v_1, t_1, t_2):
    t_list = np.arange(0, t_total, precision)
    count = 0
    for t in t_list:
        if collision_detection(get_M1_coordinate(M2, t), FY2, t, v_1, t_1, t_2, theta) == len(target_point):
            count += 1
    return count


# def set_seed(seed=308):
#     random.seed(seed)
#     os.environ["PYTHONHASHSEED"] = str(seed)
#     np.random.seed(seed)
#
#
# set_seed(308)  # 固定随机种子，方便结果复现


# 定义变量范围
lb = [2.6, 124, 0, 1, 1, 0, 0, 0]  # theta, v1, t1_0, t1_1, t1_2, t2_0, t2_1, t2_2
ub = [2.8, 130, 10, 40, 30, 10, 30, 30]


# 定义目标函数
def objective(x):
    theta, v_1, t_1_0, t_1_1, t_1_2, t_2_0, t_2_1, t_2_2 = x
    t_1 = [t_1_0, t_1_1, t_1_2]
    t_2 = [t_2_0, t_2_1, t_2_2]
    return -fun(theta, v_1, t_1, t_2)  # PSO默认最小化，所以取负


# 运行PSO
xopt, fopt = pso(objective, lb, ub, swarmsize=15, maxiter=20)

# 提取最佳解
theta_b, v_1_b, t_1_0, t_1_1, t_1_2, t_2_0, t_2_1, t_2_2 = xopt
t_1_b = [t_1_0, t_1_1, t_1_2]
t_2_b = [t_2_0, t_2_1, t_2_2]
Pb = -fopt  # 恢复目标值
print(f"F2防M2最佳解: P={Pb}, theta={theta_b}, v_1={v_1_b}, t_1={t_1_b}, t_2={t_2_b}")
